<template>
	<div class="camerbox">
		<video id="gumVideo" class="gumVideo" autoplay='autoplay' muted ref="gumVideo" v-if="camerFlag"></video>
		<video :id=playId ref="gumVideo2" class="gumVideo2"  muted v-else controls></video>
		<div class="count" v-if="camerFlag">{{ countDown }}</div>
		<div class="btnbox" >
			<div class="btn" @click="startRecord" v-if="camerFlag">

			</div>
			<div class="other" v-else>
				<div class="restart" @click="restart">重录</div>
				<div class="btn2" @click="nextStep" >
					下一步
				</div>
			</div>
			
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from "vue-router";
import { get, set, clear, del, delMany } from 'idb-keyval';//delMany([123, 'hello'])
import axios from 'axios';

const props = defineProps({
	count: {
		type: Number,
		default: 3
	},
	playId: {
		type: String,
		default: 'gumVideo2'
	},
	videoName: {
		type: String,
		default: 'front'
	},
})
const router = useRouter();
const camerFlag = ref(true);
const Timer = ref(3);//计时器
const countDown = ref(3);//倒计时

const state = reactive({
	mediaRecorder: {},
	recorderFile: {},
	stream: {},
	stopRecordCallback: null
})

const gumVideo = ref(null)
const gumVideo2 = ref(null)
onMounted(() => {
	openCamera()
})
const openCamera = () => {
	getUserMedia(function (error, stream) {
		if (error) {
			console.log(error)
		} else {
			let options = { mimeType: 'video/webm;codecs=vp9,opus' }
			if (!MediaRecorder.isTypeSupported(options.mimeType)) {
				console.log(`${options.mimeType} is not supported`)
				options = { mimeType: 'video/webmcodecs=vp8,opus' }
				if (!MediaRecorder.isTypeSupported(options.mimeType)) {
					console.log(`${options.mimeType} is not supported`)
					options = { mimeType: 'video/webm' }
					if (!MediaRecorder.isTypeSupported(options.mimeType)) {
						console.log(`${options.mimeType} is not supported`)
						options = { mimeType: '' }
					}
				}
			}
			state.mediaRecorder = new MediaRecorder(stream, options)
			state.stream = stream
			// 存储数据流
			let chunks = []
			gumVideo.value.srcObject = stream
			gumVideo.value.play()
			state.mediaRecorder.ondataavailable = e => {
				state.mediaRecorder.blobs.push(e.data)
				chunks.push(e.data)
			}
			state.mediaRecorder.blobs = []
			state.mediaRecorder.onstop = () => {
				// 数据流转换为 file
				// console.log('%caicamera.vue line:80 "stop"', 'color: #007acc;', "stop");
				state.recorderFile = getRecorderFile(chunks)
			}
		}
	})
}

const getRecorderFile = chunks => {
	const blob = new Blob(chunks, { type: state.mediaRecorder.mimeType })
	const file = new File([blob], 'recording.mp4')
	let url = URL.createObjectURL(blob)//创建文件路径
	console.log('%caicamera.vue line:92 url', 'color: #007acc;', url);
	set(props.videoName, blob)
	set('file', file)
	camerFlag.value = false
	setTimeout(() => {
	gumVideo2.value.src = url
		
	}, 10);
	console.log('%caicamera.vue line:90 file', 'color: #007acc;', file);
	return file
}

const getUserMedia = callback => {
	const constraints = { // 表示同时采集视频金和音频
		video: {
			width: 400,   // 宽带
			height: 400,  // 高度
			frameRate: 15, // 帧率
			facingMode: 'environment', //  设置为前置摄像头
		},
		audio: false // 将声音获取设为true
	}
	if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
		callback(new Error('您的浏览器暂不支持视频录制'))
	} else {
		navigator.mediaDevices
			.getUserMedia(constraints)
			.then(function (stream) {
				callback(false, stream)
			})
			.catch(function (error) {
				callback(error)
			})
	}
}
const timerInter = ref(null);
// 开始录制
const startRecord = () => {
	state.mediaRecorder.start() // start方法里面传入一个时间片，每隔一个 时间片存储 一块数据
	// setTimeout(() => {
	// 	stopRecord(state.stream);
	// }, Timer.value * 1000)

	timerInter.value = setInterval(()=>{
		countDown.value--;
		if(countDown.value === 0){
			clearInterval(timerInter.value);
			stopRecord(state.stream);
		}
	},1000)
}

// 停止录制
const stopRecord = stream => {
	state.mediaRecorder.stop()
	closeStream(stream)
}
// 关闭流
const closeStream = stream => {
	stream.getTracks().forEach(function(track) {
		track.stop();
	});
}
const bufferToDataUrl = () => {
	// console.log('recordedBlobs',recordedBlobs)
	let blob = new Blob(recordedBlobs, { type: "video/webm" });
	let file = new File([blob], 'recording.mp4')
	let url = URL.createObjectURL(blob)//创建文件路径
	set('frontvideo', blob)
	set('file', file)
	this.recordflag = false
	setTimeout(() => {
		// this.replay(url)
	}, 300);
}
const restart = () => {
    router.go(0)
}
const nextStep=()=>{
    console.log('%caicamera.vue line:172 333', 'color: #007acc;', 333);
}
</script>

<style lang="scss" scoped>
.camerbox {
	position: relative;
	width: 100%;
	height: 100vh;

	.gumVideo,
	.gumVideo2 {
		// transform: rotateY(180deg);
		width: 100%;
		height: calc(100vh - 120px);
		object-fit: fill;
		margin-top: 120px;
		// padding: 8px;
		// margin-top: 69px;

	}
	.count{
		font-size: 126px;
		position: absolute;
		top:220px;
		right: 90px;
		color: #fff;
	}

	.btnbox {
		position: absolute;
		bottom: 160px;
		left: 50%;
		transform: translateX(-50%);
		display: flex;
		justify-content: center;
		align-items: center;

		.btn {
			width: 220px;
			height: 220px;
			border-radius: 50%;
			border: 6px solid #fff;
			background-color: rgba($color: #fff, $alpha: 0.3)
		}
		.btn2,.restart{
			width: 320px;
			text-align: center;
			line-height: 120px;
			background: #4135ED;
			color: #fff;
			font-size: 50px;
			border-radius: 50px;
			margin-bottom: 40px;
		}
	}

}
</style>